package com.citycloud.ccuap.tc.admin.sec.secuser;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.citycloud.ccuap.commons.application.ApplicationGlobalNames;
import com.citycloud.ccuap.commons.db.SqlRestrictions;
import com.citycloud.ccuap.commons.json.JSONData;
import com.citycloud.ccuap.commons.json.TreeNode;
import com.citycloud.ccuap.commons.openapi.controller.base.BaseController;
import com.citycloud.ccuap.commons.sys.deptment.IDeptmentService;
import com.citycloud.ccuap.commons.sys.entity.*;
import com.citycloud.ccuap.commons.sys.group.IGroupService;
import com.citycloud.ccuap.commons.sys.project.IProjectService;
import com.citycloud.ccuap.commons.sys.repository.SysProjectRepository;
import com.citycloud.ccuap.commons.sys.repository.SysRoleRepository;
import com.citycloud.ccuap.commons.sys.repository.SysUserRepository;
import com.citycloud.ccuap.commons.sys.role.IRoleService;
import com.citycloud.ccuap.commons.sys.user.IUserService;
import com.citycloud.ccuap.commons.web.constants.ReqParamConstant;
import com.citycloud.ccuap.commons.web.util.ResolveRequest;
import com.citycloud.ccuap.framework.exception.AppAssert;
import com.citycloud.ccuap.framework.exception.ApplicationException;
import com.citycloud.ccuap.framework.mybatis.pagination.PageQuery;
import com.citycloud.ccuap.tc.admin.datagroup.IDatagroupService;
import com.citycloud.ccuap.tc.admin.entity.SysDeptmentMerge;
import com.citycloud.ccuap.tc.admin.entity.SysProjectFunction;
import com.citycloud.ccuap.tc.admin.entity.SysProjectRelApp;
import com.citycloud.ccuap.tc.admin.entity.TableCateDto;
import com.citycloud.ccuap.tc.admin.model.SecUser;
import com.citycloud.ccuap.tc.admin.permission.IFuncPermissionService;
import com.citycloud.ccuap.tc.admin.projectfunction.IProjectFunctionService;
import com.citycloud.ccuap.tc.admin.projectrelapp.SysProjectRelAppService;
import com.citycloud.ccuap.tc.admin.repository.SysDeptmentMergeRepository;
import com.citycloud.ccuap.tc.admin.repository.SysProjectAclRepository;
import com.citycloud.ccuap.tc.admin.repository.SysProjectFunctionRepository;
import com.citycloud.ccuap.tc.admin.repository.SysProjectRelAppRepository;
import com.citycloud.ccuap.tc.admin.tools.SignatureUtils;
import com.citycloud.ccuap.tc.common.result.ResultObject;
import com.citycloud.ccuap.tc.yq.constant.YqConstant;
import com.citycloud.ccuap.tc.yq.entity.SysDimensionTableConfig;
import com.citycloud.ccuap.tc.yq.metafield.MetaFieldMapper;
import com.citycloud.ccuap.tc.yq.metatable.TableMapper;
import com.citycloud.ccuap.tc.yq.repository.SysDimensionTableConfigRepository;
import com.citycloud.ccuap.tc.yq.view.TableField;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/v1/sys/user4sec")
public class SecUserController extends BaseController {

    @Autowired
    private IUserService userService;

    @Autowired
    private ISecUserService secUserService;

    @Autowired
    private IFuncPermissionService funcPermissionService;

    @Autowired
    private IUserRemoteService userRemoteService;

    @Autowired
    private IProjectService projectService;

    @Autowired
    private IGroupService groupService;

    @Autowired
    private IDeptmentService deptmentService;

    @Autowired
    private IProjectFunctionService projectFunctionService;

    @Resource
    private SysProjectFunctionRepository sysProjectFunctionRepository;

    @Resource
    private SysProjectAclRepository sysProjectAclRepository;

    @Resource
    @Lazy
    MetaFieldMapper fieldMapper;

    @Resource
    @Lazy
    TableMapper tableMapper;

    @Autowired
    ISecUserCacheService secUserCacheService;
    
    @Autowired
    SysProjectRelAppRepository sysProjectRelAppRepository;

    @Autowired
    private SysDimensionTableConfigRepository sysDimensionTableConfigRepository;

    @Autowired
    private IDatagroupService datagroupService;
    
    @Autowired
    private SysDeptmentMergeRepository sysDeptmentMergeRepository;

    @Resource
    @Lazy
    private SecUserMapper secUserMapper;

    @Autowired
    private IRoleService roleService;
    @Autowired
    private SysRoleRepository sysRoleRepository;
    @Autowired
    private SysUserRepository sysUserRepository;


    @RequestMapping(value = "/findUsersById", method = RequestMethod.GET)
    public ResultObject findUsersById() throws Exception {
        String roleCode = getStringParameter("roleCode");
        Long projectId = getLongParameter("projectId");
        SysRole sysRole = new SysRole();
        sysRole.setRoleCode(roleCode);
        sysRole.setProjectId(projectId);
        sysRole = sysRoleRepository.findByRoleCodeAndProjectId(roleCode,projectId);
        if(sysRole!=null && sysRole.getRoleId()!=null){
            List<Map<String, Object>> userList = roleService.findUsersInfoById(sysRole.getRoleId());
            return ResultObject.getInstance().success(userList);
        }else{
            return ResultObject.getInstance().error("您传输的参数有误");
        }
    }


//    @ApiOperation("获取码表")
//    @RequestMapping(
//            value = {"/getSysDictionaryList"},
//            method = {RequestMethod.GET, RequestMethod.POST}
//    )
//    public JSONData getSysDictionaryList() throws Exception {
//        String typeCode = getStringParameter("typeCode");
//        String code = getStringParameter("code");
//        Long pid = getLongParameter("pid");
//        SysDictionary sysDictionary = new SysDictionary();
//        if(StringUtils.isNotEmpty(typeCode)){
//            sysDictionary.setTypeCode(typeCode);
//        }
//        if(StringUtils.isNotEmpty(code)){
//            sysDictionary.setCode(code);
//        }
//        sysDictionary.setStatus("0");
//        sysDictionary.setPid(pid);
//        Sort sort = Sort.by(Sort.Direction.DESC,"sort");
//        List<SysDictionary> sysDictionaryList =
//                sysDictionaryRepository.findAll(
//                        sysDictionary
//                    );
////        sysDictionaryList.sort((a,b)->a.getSort().compareTo(b.getSort()));
//        JSONData jsonData = new JSONData(sysDictionaryList);
//        return jsonData;
//    }


    @ApiOperation("根据部门编号查询人员")
    @RequestMapping(
            value = {"/getUserListByDeptId"},
            method = {RequestMethod.GET, RequestMethod.POST}
    )
    public JSONData getUserListByDeptId() throws Exception {
        PageQuery<Map<String, Object>> pageQuery = ResolveRequest.getPageForParams(this.request);
        Long deptId = this.getLongParameter("q_deptId");
        String userName = this.getStringParameter("q_name");
        Long groupId = this.getLongParameter("q_groupId");
        Long projectId = this.getLongParameter("projectId");
        String sqlFilter = this.getSqlFilter();
        if (ApplicationGlobalNames.DATA_GRADE && sqlFilter == null) {
            return new JSONData(pageQuery);
        } else {
            PageQuery userList;
            if (projectId == null) {
                userList = this.userService.getUserListByDeptId(deptId, userName, pageQuery, groupId, sqlFilter);
            } else {
                userList = this.userService.getUserListByDeptIdAndProjectId(deptId, projectId, userName, pageQuery, groupId, sqlFilter);
            }

            JSONData jsonData = new JSONData(userList);
            return jsonData;
        }
    }


    @RequestMapping(value = "/buildUserProjectRole", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData buildUserProjectRole() {
        Long userId = getLongParameter("userId");
        Long projectId = getLongParameter("projectId");
        secUserCacheService.buildUserProjectRoleCache(projectId, userId);
        return new JSONData("缓存构建成功！");

    }

    @RequestMapping(value = "/getDataPermissionsOfTableByUser", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData getDataPermissionsOfTableByUser() {
        Long userId = getLongParameter("userId");
        Long projectId = getSysProjectId();
        String datasource = getStringParameter("datasource");
        AppAssert.notNull(userId,"用户ID不允许为空");

        logger.info("用户编号:" + userId + ",站点编号:" + projectId + ",数据源编号:" + datasource);

        Set<String> entity = secUserCacheService.getDataPermissionsOfTableByUser(userId, projectId, datasource);
        JSONData jsonData = new JSONData(entity);
        logger.info("获取表：" + entity);
        return jsonData;
    }

    private Long getSysProjectId(){
        Long projectId = getLongParameter("projectId");
        String accessKeyId = request.getParameter("AccessKeyId");

        if (null == projectId) {
          //  List<SysProjectRelApp> app = sysProjectRelAppRepository.findByClientId(accessKeyId);
            String sql="select project_id projectId from sys_project where client_id=\""+accessKeyId+"\"";
            List<Map<String, Object>> app = projectService.selectList(sql);
            if (CollectionUtils.isEmpty(app)) {
                throw new ApplicationException(401, YqConstant.APPID_NOT_EXISTS);
            }
            if (app.size() > 1) {
                throw new ApplicationException(401, YqConstant.PROJECT_ID_NEED);
            }
            Integer id=(Integer)app.get(0).get("projectId");
            projectId = id.longValue();
        }
        return projectId;
    }
    @RequestMapping(value = "/getDataPermissionsOfFieldByUserAndTable", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData getDataPermissionsOfFieldByUserAndTable() {
        Long userId = getLongParameter("userId");
        String datasource = getStringParameter("datasource");
        String tableValue = getStringParameter("tableValue");
        AppAssert.notNull(userId,"用户ID不允许为空");
        AppAssert.hasText(tableValue, "必须传入表名");
    
        Long projectId = getSysProjectId();

        logger.info("用户编号:" + userId + ",站点编号:" + projectId + ",数据源编号:" + datasource + ",表id:" + tableValue);
        Set<String> entity = secUserCacheService.getDataPermissionsOfFieldByUserAndTable(userId, projectId, tableValue);
        JSONData jsonData = new JSONData(entity);
        logger.info("获取字段：" + entity);
        return jsonData;
    }


    @RequestMapping(value = "/getDataPermissionsOfTableField", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData getDataPermissionsOfTableField() {
        Long userId = getLongParameter("userId");
        String datasource = getStringParameter("datasource");
        String groupNo = getStringParameter("groupNo");
        String tableValue = getStringParameter("tableValue");
        AppAssert.hasText(groupNo, "必须传入机构编码");
        AppAssert.hasText(tableValue, "必须传入表名");
        AppAssert.notNull(userId,"用户ID不允许为空");
        Long projectId = getSysProjectId();
    

        logger.info("用户编号:" + userId + ",站点编号:" + projectId + ",数据源编号:" + datasource + ",表id:" + tableValue);

        TableField entity = secUserCacheService.getDataPermissionsOfTableField(userId, projectId, tableValue, groupNo);
        JSONData jsonData = new JSONData(entity);
        logger.info("获取表字段:" + entity);
        return jsonData;
    }


    @RequestMapping(value = "/cacheUserDataPermissions", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData cacheUserDataPermissions() {
        String userId = getStringParameter("userId");
        AppAssert.hasText(userId, "必须传入用户编号");

        String projectId = getStringParameter("projectId");
        AppAssert.hasText(projectId, "必须传入站点编号");

        userRemoteService.cacheUserDataPermissions(userId, projectId);
        JSONData jsonData = new JSONData("触发用户站点的缓存！");
        return jsonData;
    }

    /**
     * 获取用户信息
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/findById", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData findById() throws Exception {
        Long userId = getLongParameter("userId");
        AppAssert.notNull(userId,"用户ID不允许为空");
        Long projectId = getSysProjectId();

        SecUser secUser = secUserService.getUser("" + userId, "" + projectId);
        if(secUser!=null) {
            secUser.clearSecUser();
            return new JSONData(secUser);
        }

        return new JSONData(false,"用户不存在");
    }

    /**
     * 获取用户信息
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/findUserInfoByUserNo", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData findUserInfoByUserNo() throws Exception {
        String userNo = getStringParameter("userNo");
        SysUser user = sysUserRepository.findByUserNo(userNo);
        Long projectId = getSysProjectId();
        SecUser secUser = secUserService.getUser(String.valueOf(user.getUserId()),String.valueOf(projectId));

//        SecUser secUser = secUserService.getUser("" + user.getUserId(), "" + projectId);
        if(secUser!=null) {
            secUser.clearSecUser();
            return new JSONData(secUser);
        }

        return new JSONData(false,"用户不存在");
    }


    /**
     * 1 获取某机构下拥有指定角色的用户
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getUsersInRoles", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData getUsersInRoles() throws Exception {
        //机构(部门)id
        String orgId = getStringParameter("orgId");
        //项目id
        String projectId = getStringParameter("projectId");
        //角色Id
        String roleId = getStringParameter("roleId");
        List<SecUser> secUsers = secUserService.getUsersInRoles(orgId, projectId, roleId);
        JSONData jsonData = new JSONData(secUsers);
        return jsonData;
    }

    /**
     * * 验证是否拥有指定一个角色
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/hasRole", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData hasRole() throws Exception {
        String userId = getStringParameter("userId");
        String projectId = getStringParameter("projectId");
        //正确错误各一个
        String roleId = getStringParameter("roleId");
        boolean isPermitted = secUserService.hasRole(userId, projectId, roleId);
        JSONData jsonData = new JSONData(isPermitted);
        return jsonData;
    }


    /**
     * * 验证是否拥有指定角色(之一)
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/hasRoles", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json; charset=UTF-8")
    public JSONData hasRoles(@RequestBody List<String> roles) throws Exception {
        String userId = getStringParameter("userId");
        String projectId = getStringParameter("projectId");

        boolean isPermitted = secUserService.hasRoles(userId, projectId, roles);
        JSONData jsonData = new JSONData(isPermitted);
        return jsonData;
    }

    /**
     * * 验证是否拥有指定角色所有
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/hasAllRoles", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData hasAllRoles(@RequestBody List<String> roles) throws Exception {
        String userId = getStringParameter("userId");
        String projectId = getStringParameter("projectId");
        boolean isPermitted = secUserService.hasAllRoles(userId, projectId, roles);
        JSONData jsonData = new JSONData(isPermitted);
        return jsonData;
    }


    /**
     * 11验证当前用户是否拥有对应功能权限
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/isPermitted", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData isPermittedSingle() throws Exception {
        String userId = getStringParameter("userId");
        String projectId = getStringParameter("projectId");
        String permission = getStringParameter("permission");

        boolean isPermitted = funcPermissionService.isPermitted(userId, projectId, permission);
        JSONData jsonData = new JSONData(isPermitted);
        return jsonData;
    }

    /**
     * * 12验证当前用户是否拥有对应功能权限(多个)
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/isPermittedAll", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData isPermittedAll(@RequestBody List<String> permissions) throws Exception {
        String userId = getStringParameter("userId");
        String projectId = getStringParameter("projectId");
        boolean isPermitted = funcPermissionService.isPermittedAll(userId, projectId, permissions);
        JSONData jsonData = new JSONData(isPermitted);
        return jsonData;
    }

    /**
     * 4 判断用户是否拥有指定功能授权集合其中之一
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/hasFunctionPermissions", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json; charset=UTF-8")
    public JSONData hasFunctionPermissions(@RequestBody List<String> permissions) throws Exception {
        String userId = getStringParameter("userId");
        String projectId = getStringParameter("projectId");
        boolean isPermitted = funcPermissionService.hasFunctionPermissions(userId, projectId, permissions);
        JSONData jsonData = new JSONData(isPermitted);
        return jsonData;
    }

    /**
     * 5 判断用户是否拥有指定功能授权集合所有
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/hasAllFunctionPermissions", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json; charset=UTF-8")
    public JSONData hasAllFunctionPermissions(@RequestBody List<String> permissions) throws Exception {
        String userId = getStringParameter("userId");
        String projectId = getStringParameter("projectId");
        boolean isPermitted = funcPermissionService.hasAllFunctionPermissions(userId, projectId, permissions);
        JSONData jsonData = new JSONData(isPermitted);
        return jsonData;
    }


    @RequestMapping(value = "/getProjectFunsByUserIdAndProjectId", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json; charset=UTF-8")
    public JSONData getProjectFunsByUserIdAndProjectId() {
        
        Long userId = getLongParameter("userId");
        AppAssert.notNull(userId,"用户ID不允许为空");

        String projectId = "" + getSysProjectId();
        
        List<SysRole> roles = secUserService.findProjectRoles(projectId,"" +  userId);
        if (roles.size() == 0) {
            return new JSONData(new ArrayList<TreeNode>());
        }
        StringBuilder roleids = new StringBuilder();
        roles.forEach(r -> roleids.append(r.getRoleId()).append(","));
        roleids.setLength(roleids.length() - 1);
        return new JSONData(secUserService.findProjectTreeNodesByRoles(projectId, roleids.toString(), null));
    }

    @RequestMapping(value = "/getProjectFunsSetByUserIdandProjectId", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json; charset=UTF-8")
    public JSONData getProjectFunsSetByUserIdandProjectId() {
        Long userId = getLongParameter("userId");
        Long projectId = getLongParameter("projectId");
        return new JSONData(secUserService.findProjectFunsSetByUserIdandProjectId(projectId, userId));
    }

    private String getAllPathName(SysUser user) {
        SysGroup group = groupService.findById(user.getGroupId());
        SysDeptment deptment = deptmentService.findById(user.getDeptId());
        StringBuilder sb = new StringBuilder();
        if (null != group) {
            sb.append(group.getFullPath()).append("\\");
        }
        if (null != deptment) {
            sb.append(deptment.getFullPath()).append("\\");
        }
        sb.append(user.getUserName());
        return sb.toString();
    }

    /**
     * 获取当前站点所有角色
     *
     * @return
     */
    @RequestMapping(value = "/getRolesByProjectId", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json; charset=UTF-8")
    public JSONData getRolesByProjectId() {
        String projectId = getStringParameter("projectId");
        List<SysRole> roles = secUserService.getRolesByProjectId(Long.valueOf(projectId));
        List<Map<String, String>> result = new ArrayList<>();
        roles.forEach((role) -> {
            Map<String, String> r = new HashMap<>();
            r.put("roleId", role.getRoleId().toString());
            r.put("roleName", role.getRoleName());
            result.add(r);
        });
        return new JSONData(result);
    }

    /**
     * 获取某个角色的所有人员
     *
     * @return
     */
    @RequestMapping(value = "/getUsersByRoleId", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json; charset=UTF-8")
    public JSONData getUsersByRoleId() {
        String roleId = getStringParameter("roleId");
        List<SysUser> users = secUserService.getUsersByRoleId(Long.valueOf(roleId));
        List<Map<String, String>> result = new ArrayList<>();
        users.forEach((user) -> {
            Map<String, String> u = new HashMap<>();
            u.put("userId", user.getUserId().toString());
            u.put("allPathName", getAllPathName(user));
            result.add(u);
        });
        return new JSONData(result);
    }

    /**
     * 该用户具有某种角色的站点信息列表
     *
     * @param roleCode 角色code
     * @param userId   用户id
     * @return
     */
    @RequestMapping(value = "/getWebSitesByRoleCodeAndUserId")
    public JSONData getWebSitesByRoleIdAndUserId(@RequestParam(value = "roleCode") String roleCode, @RequestParam("userId") String userId) {
        List<Map<String, Object>> webSiteList = secUserService.getWebSitesByRoleIdAndUserId(userId, roleCode);
        return new JSONData(webSiteList);
    }


    /**
     * 根据名称查询人员信息
     *
     * @return
     */
    @RequestMapping(value = "/getUsersByUserName", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json; charset=UTF-8")
    public JSONData getUsersByUserName() {
        String userName = getStringParameter("userName");
        List<SysUser> users = secUserService.getUsersByUserName(userName);
        List<Map<String, String>> result = new ArrayList<>();
        users.forEach((user) -> {
            Map<String, String> u = new HashMap<>();
            u.put("userId", user.getUserId().toString());
            u.put("allPathName", getAllPathName(user));
            result.add(u);
        });
        return new JSONData(result);
    }

    @ApiOperation("根据用户userGuid 返回用户身份列表")
    @RequestMapping(value = "/getUserInfo", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData getUserInfo() {
        String userGuid = dealWithString(getStringParameter("userGuid"));
        Long projectId = dealWithLong(getStringParameter("projectId"));
        String sql = "SELECT user.user_id, user.dept_id, dept.full_path FROM sys_user AS user LEFT JOIN sys_deptment AS dept ON user.dept_id = dept.dept_id where 1=1 ";
        sql += SqlRestrictions.eq("user.project_id", projectId);
        sql += SqlRestrictions.eq("user.user_guid", userGuid);
        List<Map<String, Object>> list = userService.selectList(sql);
        JSONData result = new JSONData(list);
        return result;
    }

    private String dealWithString(String s) {
        return "null".equals(s) || StringUtils.isBlank(s) ? "" : s;
    }

    private Long dealWithLong(String s) {
        return ("null".equals(s) || StringUtils.isBlank(s)) ?
                null : Long.valueOf(s);
    }

    @ApiOperation("身份切换")
    @RequestMapping(value = "/changeIdentity", method = RequestMethod.POST)
    public JSONData changeIdentity() throws Exception {
        Long userId = Long.valueOf((getStringParameter("userId")));
        String userGuid = getStringParameter(ReqParamConstant.USERGUID_KEY);
        userService.executeUpdate("update sys_user set enabled=1 where user_id=" + userId);
        userService.executeUpdate("update sys_user set enabled=0 where user_guid='" + userGuid + "' and user_id <>" + userId);
        return new JSONData("身份切换成功！");
    }

    @ApiOperation("根据条件获取站点信息")
    @RequestMapping(value = "/getSysProjectsByConditions", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData getSysProjectsByConditions() {
        Long managerId = dealWithLong(getStringParameter("managerId"));
        Long cateId = dealWithLong(getStringParameter("cateId"));
        String name = dealWithString(getStringParameter("name"));
        JSONData result = new JSONData(secUserService.getSysProjectsByConditions(managerId, cateId, name));
        return result;
    }

    @ApiOperation("修改指定站点的名称，备注")
    @RequestMapping(value = "/updateSysProject", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData updateSysProject() {
        Long id = dealWithLong(getStringParameter("id"));
        String name = dealWithString(getStringParameter("name"));
        String remark = dealWithString(getStringParameter("remark"));
        SysProject sysProject = projectService.findById(id);
        if (StringUtils.isNotBlank(name)) {
            sysProject.setProjectName(name);
        }
        sysProject.setRemark(remark);
        JSONData result = new JSONData(projectService.save(sysProject));
        return result;
    }

    @ApiOperation("根据条件获取站点信息")
    @RequestMapping(value = "/getManagersByProjectId", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData getManagersByProjectId() {
        Long projectId = dealWithLong(getStringParameter("projectId"));
        JSONData result = new JSONData(secUserService.getManagersByProjectId(projectId));
        return result;
    }

    @ApiOperation("根据条件获取站点分类树")
    @RequestMapping(value = "/getProjectCategoryTree", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData getProjectCategoryTree() {
        JSONData result = new JSONData(secUserService.findNextChildNodeTree(null, true));
        return result;
    }

    @ApiOperation("导入系统树")
    @RequestMapping(value = "/importSysFun", method = {RequestMethod.POST})
    public JSONData importSysFun(@RequestBody List<String> data) {
        JSONObject obj = null;
        if (data.size() > 0) {
            obj = JSON.parseObject(data.get(0));
            ;
        } else {
            return new JSONData(false);
        }
        logger.debug("导入菜单树参数：" + obj);
        Long projectId = obj.getLong("tenId");
        String pid = StringUtils.isNotBlank(obj.getString("pid")) ? obj.getString("pid") : ("YUNNAO_" + projectId);
        JSONArray menus = obj.getJSONArray("menu");

        // fun_id 组成  F_站点ID_链接类型（1 功能集合 2 功能）_code
        for (int i = 0; i < menus.size(); i++) {
            JSONObject menu = menus.getJSONObject(i);
            String pcode = menu.getString("code");
            String pfunid = combinFunctionId(projectId, "1", pcode);
            JSONArray submenus = menu.getJSONArray("submenu");
            if (menu.getBoolean("deleted")) {
                for (int j = 0; j < submenus.size(); j++) {
                    JSONObject submenu = submenus.getJSONObject(j);
                    String id = combinFunctionId(projectId, "2", submenu.getString("code"));
                    SysProjectFunction subFunction = sysProjectFunctionRepository.findByFunId(id);
                    projectFunctionService.deleteById(subFunction.getPrjFunId());
                    sysProjectAclRepository.deleteByPrjFunId(subFunction.getPrjFunId());
                    SysProjectFunction pFunction = new SysProjectFunction();
                    pFunction.setPid(pfunid);
                    if (projectFunctionService.selectList(pFunction).size() == 0) {
                        SysProjectFunction subpFunction = sysProjectFunctionRepository.findByFunId(pfunid);
                        projectFunctionService.deleteById(subpFunction.getPrjFunId());
                        sysProjectAclRepository.deleteByPrjFunId(subpFunction.getPrjFunId());
                    }
                }
            } else {
                SysProjectFunction pFunction = sysProjectFunctionRepository.findByFunId(combinFunctionId(projectId, "1", pcode));
                if (null == pFunction) {
                    pFunction = new SysProjectFunction();
                    pFunction.setProjectId(projectId);
                    pFunction.setFunId(pfunid);
                    pFunction.setFunName(menu.getString("name"));
                    pFunction.setFunType((short) 1);
                    pFunction.setLocation(menu.getString("url"));
                    pFunction.setPid(pid);
                    pFunction.setOrderNo((long) i);
                    pFunction.setLogFlag((short) 1);
                    String fullpath = getFullPath(pid, projectId) + "/" + menu.getString("name");
                    pFunction.setFullPath(fullpath);
                    projectFunctionService.insert(pFunction);
                }
                for (int j = 0; submenus != null && j < submenus.size(); j++) {
                    JSONObject submenu = submenus.getJSONObject(j);
                    String subfunid = combinFunctionId(projectId, "2", submenu.getString("code"));
                    SysProjectFunction subFunction = sysProjectFunctionRepository.findByFunId(subfunid);
                    if (null == subFunction) {
                        subFunction = new SysProjectFunction();
                        subFunction.setProjectId(projectId);
                        subFunction.setFunId(subfunid);
                        subFunction.setFunName(submenu.getString("name"));
                        subFunction.setFunType((short) 2);
                        subFunction.setLocation(submenu.getString("url"));
                        subFunction.setPid(pfunid);
                        subFunction.setOrderNo((long) i);
                        subFunction.setLogFlag((short) 1);
                        String fullpath = getFullPath(pfunid, projectId) + "/" + submenu.getString("name");
                        subFunction.setFullPath(fullpath);
                        projectFunctionService.insert(subFunction);
                    }
                }
            }
        }
        JSONData result = new JSONData(true);
        return result;
    }

    private String combinFunctionId(Long projectId, String type, String code) {
        return new StringBuilder("F").append(projectId).append("_").append(type).append("_").append(code).toString();
    }

    @ApiOperation("获取有用户权限的租户")
    @RequestMapping(value = "/getProjectsByUserRoles", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData getProjectsByUserRoles() {
        Long userId = getLongParameter("userId");
        return new JSONData(secUserService.getProjectsByUserRoles(userId));
    }

    @ApiOperation("获取所有站点信息列表")
    @RequestMapping(value = "/getAllProjects", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData getAllProjects() {
        JSONData result = new JSONData(secUserService.getAllProjects());
        return result;
    }

    /**
     * 获取部门树
     *
     * @return
     */
    @RequestMapping(value = "/getDeptTree", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json; charset=UTF-8")
    public JSONData getDeptTree() {
        String id = getStringParameter("id");
        String type = getStringParameter("type");
        List<Map<String, Object>> result = secUserService.getDeptTree(id, type, 2);
        return new JSONData(result);
    }

    @RequestMapping(value = "/testpath", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json; charset=UTF-8")
    public String getFullPath(String pid, Long projectId) {
        try {
            SysProjectFunction function = sysProjectFunctionRepository.findByFunIdAndProjectId(pid, projectId);
            System.out.println(function.getFunName());
            List<String> path = Lists.newArrayList();
            if (StringUtils.isNotBlank(function.getPid())) {
                String pathname = getFullPath(function.getPid(), projectId) + "/" + function.getFunName();
                return pathname;
            }
            return function.getFunName();
        } catch (Exception e) {

            return e.getMessage();
        }

    }

    /**
     * 清空缓存
     *
     * @return
     */
    @RequestMapping(value = "/clearCache", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData clearCache() {
        String userId = getStringParameter("userId");
        String projectId = getStringParameter("projectId");
        String datagroupId = getStringParameter("datagroupId");
        Integer isAll = getIntParameter("isAll");
        if (isAll.equals(YqConstant.ALL)) {
            secUserService.clearAllCache(userId, projectId);
            List<Map<String, Object>> list = new ArrayList<>();
            String userSql = "select user_id,project_id from sys_user where data_status=1 and project_id is not null";
            List<Map<String, Object>> userList = userService.selectList(userSql, true);
            list.addAll(userList);
            String sql = "select user_id,project_id from sys_user_dept_rel where 1=1";
            List<Map<String, Object>> users = userService.selectList(sql, true);
            list.addAll(users);
            list.stream().distinct().forEach(map -> {
                fieldMapper.getDataGroup(map.get("userId").toString(), map.get("projectId").toString());
            });
        } else if (StringUtils.isNotEmpty(userId) && StringUtils.isNotEmpty(projectId)) {
            secUserService.clearCache(userId, projectId);
            fieldMapper.getDataGroup(userId, projectId);
        } else {
            secUserService.clearCacheDatagroupIdAndProjectId(datagroupId);
            tableMapper.getTableByDatagroupId(datagroupId);
            List<SysDimensionTableConfig> list = sysDimensionTableConfigRepository.findByDatagroupId(datagroupId);
            list.stream().forEach(x -> {
                fieldMapper.getFieldByTableConfigId(x.getTableConfigId());
            });
        }
        return new JSONData("执行成功！");
    }

    
    @RequestMapping(value = "/buildCache", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json; charset=UTF-8")
    public JSONData buildCache() {
        secUserCacheService.buildAllDataGroupAndRoleCache();
        return new JSONData("执行成功！");
    }
    
    
    @RequestMapping(value = "/rebuildSynCache", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json; charset=UTF-8")
    public JSONData rebuildSynCache() {
        secUserService.getDeptmentsByPid(-1L, true);
        secUserService.getUsersByDeptId(-1L, true);
        return new JSONData("执行成功！");
    }

    @RequestMapping(value = "/rebuildDatagroupCacheByTableId", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json; charset=UTF-8")
    public JSONData rebuildCacheByTableId() {
        String tableId = getStringParameter("tableValue");
        secUserCacheService.rebuildDatagroupCacheByTableId(tableId);
        return new JSONData("执行成功！");
    }

    @ApiOperation("根据用户id获取该用户的所有站点")
    @RequestMapping(value = "/getAllProjectByUserId", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json; charset=UTF-8")
    public JSONData getAllProjectByUserId() {
        String userId = getStringParameter("userId");
        List<SysProject> sysProjects = secUserService.selectAllProjectByUserId(userId);
        if (sysProjects.size() == 0) {
            return new JSONData(new ArrayList<SysProject>());
        }
        return new JSONData(sysProjects);
    }

    @ApiOperation("根据用户id,站点id,分类id获取有权限表信息(cateId,cateName,tableCname),分类id不传则默认返回一级分类")
    @RequestMapping(value = "/getTablePermissionsByUser", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json; charset=UTF-8")
    public JSONData getTablePermissionsByUser() {
        String userId = getStringParameter("userId");
        String projectId = getStringParameter("projectId");
        String cateId = getStringParameter("cateId");
        List<TableCateDto> tableCateDtos = secUserService.getTablePermissionsByUser(userId, projectId, cateId);
        if (tableCateDtos.size() == 0) {
            return new JSONData(new ArrayList<TableCateDto>());
        }
        return new JSONData(tableCateDtos);
    }

    @ApiOperation("根据站点id获取站点管理员信息,若不传站点id则获取平台级管理员信息")
    @RequestMapping(value = "/getManageUserByProjectId", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json; charset=UTF-8")
    public JSONData getManageUserByProjectId() {
        String projectId = getStringParameter("projectId");
        List<SysUser> sysUsers = secUserService.getManageUserByProjectId(projectId);
        if (sysUsers.size() == 0) {
            return new JSONData(new ArrayList<SysUser>());
        }
        return new JSONData(sysUsers);
    }


    /**
     * 查看当前用户是否有平台管理员的角色
     *
     * @return
     */
    @ApiOperation("查看当前用户是否有平台管理员的角色")
    @RequestMapping(value = "/getUserIsPlatAdmin", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json; charset=UTF-8")
    public JSONData getUserIsPlatAdmin() {
        List<SysRole> roles = secUserService.findProjectRoles(getStringParameter("projectId"), getStringParameter("userId"));
        List<SysRole> collect = roles.stream().filter(s -> "PTGLY".equals(s.getRoleCode())).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(collect)) {
            return new JSONData(true);
        } else {
            return new JSONData(false);
        }
    }
    
    @ApiOperation("获取某一个部门下的所有部门以及子部门,若不传部门PID参数则获取所有的部门")
    @RequestMapping(value = "/getDeptmentsByDeptId", method = {RequestMethod.POST}, produces = "application/json; charset=UTF-8")
    public JSONData getDeptmentsByDeptId() {
    
        
        Long deptId = getLongParameter("deptId");
    
        if (null == deptId) {
            deptId = -1L;
        }
        return new JSONData(secUserService.getDeptmentsByPid(deptId,false));
    }
    
    @ApiOperation("获取某一个部门下的所有人员")
    @RequestMapping(value = "/getUsersByDeptId", method = {RequestMethod.POST}, produces = "application/json; charset=UTF-8")
    public JSONData getUsersByDeptId() {
        
        Long deptId = getLongParameter("deptId");
        if (null == deptId) {
            return new JSONData(false, "请输入部门ID参数！");
        }
    
        return new JSONData(secUserService.getUsersByDeptId(deptId,false));
    }
    
    @ApiOperation("获取某一个部门下的所有部门,不包含子部门 若不传部门PID则获取根节点数据")
    @RequestMapping(value = "/getDirectDeptmentsByDeptId", method = {RequestMethod.POST}, produces = "application/json; charset=UTF-8")
    public JSONData getDirectDeptmentsByDeptId() {
        
        
        Long deptId = getLongParameter("deptId");
        List<SysDeptmentMerge> deptmentMerges;
        if (null == deptId) {
            deptmentMerges = sysDeptmentMergeRepository.findListByPidIsNull();
        } else {
            deptmentMerges = sysDeptmentMergeRepository.findListByPid(deptId);
        }
        return new JSONData(deptmentMerges);
    }
    
    @ApiOperation("获取某一个部门下的人员仅限于当前部门不包含子部门的人员")
    @RequestMapping(value = "/getDirectUsersByDeptId", method = {RequestMethod.POST}, produces = "application/json; charset=UTF-8")
    public JSONData getDirectUsersByDeptId() {
        
        Long deptId = getLongParameter("deptId");
        if (null == deptId) {
            return new JSONData(false, "请输入部门ID参数！");
        }
        List<Map<String, Object>> temp = secUserMapper.getListUsersByDeptId(deptId);
        return new JSONData(temp);
    }
    
    @ApiOperation("获取所有关区代码和关区名称,若oriCustom非空则查询所有大关区")
    @RequestMapping(value = "/getAllCustomCode", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json; charset=UTF-8")
    public JSONData getAllCustomCode() {
        String oriCustom = getStringParameter("oriCustom");
        List<SysGroup> groupList = secUserService.getAllCustomCode(oriCustom);
        return new JSONData(groupList);
    }
    
    @ApiOperation("根据关区代码获取关区名称")
    @RequestMapping(value = "/findByGroupNo", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json; charset=UTF-8")
    public JSONData findByGroupNo() {
        String groupNo = getStringParameter("groupNo");
        List<SysGroup> groupList = secUserService.findByGroupNo(groupNo);
        return new JSONData(groupList);
    }
    
    @ApiOperation("获取所有站点(包含所有状态)")
    @RequestMapping(value = "/getAllSysProjects", method = {RequestMethod.GET, RequestMethod.POST}, produces = "application/json; charset=UTF-8")
    public JSONData getAllSysProjects() {
        List<SysProject> projects = projectService.selectList();
        return new JSONData(projects);
    }

    /**
     * 根据站点id和姓名获取用户
     * @return
     */
    @RequestMapping(value = {"/queryUser"}, method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData queryUser() {
        Integer currPage = this.getIntParameter("currPage");
        Integer pageLimit = this.getIntParameter("pageLimit");
        AppAssert.notNull(currPage,"currPage不能为空");
        AppAssert.notNull(pageLimit,"pageLimit不能为空");
        //云擎默认第一页传0,这里做个转换
        PageQuery<Map<String, Object>> pageQuery = new PageQuery<>(currPage + 1, pageLimit);
        String name = this.getStringParameter("userName");
        Long projectId = this.getLongParameter("projectId");
        String sql = "SELECT * FROM ( SELECT su.created_time,su.user_id userId, su.user_no userNo, su.user_name userName, " +
                "sd.dept_name deptName,sg.group_name groupName FROM sys_group sg " +
                "INNER JOIN sys_user su on sg.group_id = su.group_id LEFT JOIN sys_deptment sd on su.dept_id=sd.dept_id WHERE 1=1 ";
        sql = sql + SqlRestrictions.eq("su.project_id", projectId);
        if (org.springframework.data.mybatis.repository.util.StringUtils.isNotEmpty(name)) {
            sql = sql + " AND (su.user_no like '%" + name + "%' or su.user_name like '%" + name + "%')";
        }

        sql = sql + " UNION SELECT su.created_time,su.user_id userId, su.user_no userNo, su.user_name userName, " +
                "sd.dept_name deptName, sg.group_name groupName FROM sys_deptment sd, sys_group sg, sys_user su, sys_user_dept_rel sa " +
                "WHERE sa.dept_id = sd.dept_id AND sd.group_id = sg.group_id AND su.user_id = sa.user_id ";
        sql = sql + SqlRestrictions.eq("sa.project_id", projectId);
        if (org.springframework.data.mybatis.repository.util.StringUtils.isNotEmpty(name)) {
            sql = sql + " AND (su.user_no like '%" + name + "%' or su.user_name like '%" + name + "%')";
        }
        sql = sql + ") userData";
        sql = sql + SqlRestrictions.order("userData.created_time", Sort.Direction.DESC);
        PageQuery<Map<String, Object>> pageData = datagroupService.selectPage(pageQuery, sql);
        JSONData jsonData = new JSONData(pageData);
        return jsonData;
    }

    /**
     * 根据站点名称获取站点信息
     * @return
     */
    @RequestMapping(value = {"/queryWebsite"}, method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData queryWebsite() {
        Integer currPage = this.getIntParameter("currPage");
        Integer pageLimit = this.getIntParameter("pageLimit");
        AppAssert.notNull(currPage,"currPage不能为空");
        AppAssert.notNull(pageLimit,"pageLimit不能为空");
        //云擎默认第一页传0,这里做个转换
        PageQuery<Map<String, Object>> pageQuery = new PageQuery<>(currPage + 1, pageLimit);
        String name = this.getStringParameter("websiteName");
        String sql = "select project_id projectId, project_name projectName from sys_project where 1=1";
        if (org.springframework.data.mybatis.repository.util.StringUtils.isNotEmpty(name)) {
            sql = sql + " and project_name like '%" + name + "%'";
        }
        sql = sql + SqlRestrictions.order("created_time", Sort.Direction.DESC);
        PageQuery<Map<String, Object>> pageData = datagroupService.selectPage(pageQuery, sql);
        JSONData jsonData = new JSONData(pageData);
        return jsonData;
    }
    
    /**
     * 获取服务器时间
     *
     * @return
     */
    @RequestMapping(value = {"/getServerTime"}, method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData getServerTime() {
        Long time = System.currentTimeMillis();
        JSONData jsonData = new JSONData(time);
        return jsonData;
    }
    
    /**
     * 接口校验测试
     *
     * @return
     */
    @RequestMapping(value = {"/testInterface"}, method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData testInterface() {
        Long time = System.currentTimeMillis();
        JSONObject jsonObject = new JSONObject();
        String md5str = SignatureUtils.getTestSignatureStr(time, request);
        jsonObject.put("params", request.getParameterMap());
        jsonObject.put("md5str", md5str);
        jsonObject.put("timeStamp", time);
        jsonObject.put("md5", DigestUtils.md5Hex(md5str));
        JSONData jsonData = new JSONData(jsonObject);
        return jsonData;
    }

    @ApiOperation("根据用户id,站点id获取用户信息")
    @RequestMapping(value = "/findUserByUserIdAndProjectId", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData findUserByUserIdAndProjectId(@RequestParam(value = "userId") String userId,
                                                 @RequestParam(value = "projectId") String projectId) {
        SecUser secUser = secUserService.getUser(userId, projectId);
        return new JSONData(secUser);
    }

    @ApiOperation("根据用户id,站点id,分类id获取有权限表信息(cateId,cateName,tableCname),分类id不传则默认返回一级分类")
    @RequestMapping(value = "/getTablePermissionsByUserNew", method = {RequestMethod.GET, RequestMethod.POST})
    public JSONData getTablePermissionsByUserNew(@RequestParam(value = "userId") String userId,
                                                 @RequestParam(value = "projectId") String projectId,
                                                 @RequestParam(value = "cateId") String cateId) {
        List<TableCateDto> tableCateDtos = secUserService.getTablePermissionsByUserNew(userId, projectId);
        if (tableCateDtos.size() == 0) {
            return new JSONData(new ArrayList<TableCateDto>());
        }
        return new JSONData(tableCateDtos);
    }
}
